//index.js
//获取应用实例
const app = getApp()

const SongList = [
  {
    id:0,
    title:'song-01',
    src:'https://stream.hndt.com/vod/_definst_/mp4:xinwen/20200701/xinwen_20200701_1300_1315.mp4/playlist.m3u8'
    
  },
  {
    id:1,
    title:'song-02',
    src:'https://stream.hndt.com/vod/_definst_/mp4:xinwen/20200701/xinwen_20200701_1315_1400.mp4/playlist.m3u8'
  },
  {
    id:2,
    title:'song-03',
    src:'https://stream.hndt.com/vod/_definst_/mp4:xinwen/20200701/xinwen_20200701_1215_1300.mp4/playlist.m3u8'
  },
  
]

const Bgm = wx.getBackgroundAudioManager()
Bgm.protocol = 'hls'

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    currentTime:'',
    duration:'',
    status:false,
    playIdx:0,
    playTitle:'',
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    this.playerEventInit()
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  playerEventInit() {
    
    Bgm.onCanplay(() => {
      console.log('can play')
      
    })
    Bgm.onTimeUpdate(() => {
      let {currentTime,duration} = Bgm
      this.setData({
        currentTime,
        duration
      })
    })
    Bgm.onEnded(() => {
      console.log('player end')
      let idx = this.data.playIdx
      console.log('end---',Bgm.duration)
      if(Bgm.duration > 0) {
        this.setData({
          playIdx:++idx
        },() => {
          console.log('next')
          this.setPlayerSrc()
        })
      }
    })
    Bgm.onPause(() => {
      this.setData({
        status:false
      })
    })
    Bgm.onPlay(() => {
      this.setData({
        status:true
      })
    })
    
    
  },
  setPlayerSrc(){
    console.log(this.data.playIdx)
    let {title,src} = SongList[`${this.data.playIdx}`]
    this.setData({
      motto:title
    })
    Bgm.title=title
    Bgm.src=src
    
    console.log(Bgm)
   
  },
  seekPlayerTime(e){
    console.log(e.detail.value)
    let {duration} =Bgm
    Bgm.seek(e.detail.value/100 * duration)
  }
})
